<template>
  <div class="background"></div>
  <div>
    <el-container>
      <el-header>
        <el-row :gutter="24">
          <el-col :span="7"></el-col>
          <el-col :span="3">
            <el-select v-model="currentOption" class="header-input">
              <el-option
                v-for="item in optionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option> </el-select
          ></el-col>
          <el-col :span="6">
            <el-autocomplete
                class="header-input"
              clearable
              :value-key="
                currentOption == 1
                  ? 'commonName' // : currentOption == 2 // ? 'genusName'
                  : 'familyName'
              "
              v-model="name"
              prefix-icon="search"
              :trigger-on-focus="false"
              :fetch-suggestions="getAutocomplete"
              :placeholder="`请输入${
                currentOption == 1
                  ? '植物名称'
                  : // : currentOption == 2
                    // ? '属性名称'
                    '科目名称'
              }`"
            >
              <template #append>
                <el-button
                  icon="search"
                  @click="searchPlant(name, currentOption)"
                >
                  搜索
                </el-button>
              </template>
            </el-autocomplete>
          </el-col>
          <el-col :span="5"></el-col>
          <el-col :span="2">
            <template v-if="!token">
              <el-link @click="toView('/login?redirect=/index')"
              >请先登录
              </el-link>
            </template>
            <el-dropdown v-else>
              <el-avatar
                  size="large"
                  src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
              >
              </el-avatar>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showPage">
                    修改密码
                  </el-dropdown-item>
                  <el-dropdown-item @click="toView('/admin/aside')"
                  >进入管理端
                  </el-dropdown-item>
                  <el-dropdown-item @click="toView('/register')"
                  >注册
                  </el-dropdown-item>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
      </el-header>
      <el-container class="main">
        <el-row :gutter="24">
          >
          <el-col :span="5">
            <el-cascader-panel
                v-if="currentOption == 3"
              v-model="current"
              :options="familyList"
              :props="config"
                @change="changSearch"/>
            <el-cascader-panel
                v-else
                v-model="currentName"
                :options="cropList"
                :props="cropConfig"
                @change="changName"
          /></el-col>

          <el-col :span="15"
            ><el-scrollbar height="85vh"><router-view /> </el-scrollbar
          ></el-col>
          <el-col :span="3" class="right-main">
            <h3>你可能感兴趣的人</h3>
            <el-scrollbar class="scroll-content"
              ><el-avatar
                v-for="item in avatarList"
                :key="item.url"
                :src="item.url"
                :size="item.size"
              >
              </el-avatar
            ></el-scrollbar>
            <h3>相关文献</h3>
            <el-scrollbar class="message_scrollbar">
              <p v-for="doc in documentList" :key="doc.name">
                <el-link @click="getDocumentById(doc)" type="success">
                  {{ doc.name }}
                </el-link>
              </p>
            </el-scrollbar>
          </el-col>
        </el-row>
      </el-container>
    </el-container>
    <el-dialog v-model="updatePasswordVisible" title="修改密码" width="500">
      <el-form :model="userForm" ref="userForm" :rules="rules">
        <el-form-item label="旧密码" prop="password">
          <el-input
              show-password
              v-model="userForm.password"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="userForm.newPassword"
              autocomplete="off"
              show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
              v-model="userForm.checkPassword"
              autocomplete="off"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updatePasswordVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword(userForm)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import store from "@/store/index";
import {dayjs, ElMessageBox} from "element-plus";
import {getToken, removeToken} from "@/utils/auth";
import {getUserByToken, updatePassword} from "@/api/user";

export default {
  data() {
    return {
      hover: false,
      familyList: [],
      cropList: [],
      doc: {
        current: 1,
        size: 10
      },
      updatePasswordVisible: false,
      rules: {
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }
        ],
        newPassword: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "blur"
          }
        ],
        checkPassword: [
          {
            required: true,
            message: "请再次输入密码",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请再次输入密码"));
              } else if (value !== this.userForm.newPassword) {
                callback(new Error("两次输入密码不一致!"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      userForm: {},
      currentName: "水稻",
      documentList: [],
      currentUser: {},
      avatarList: [
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        },
        {
          url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        }
      ],
      optionList: [
        { label: "按名称查询", value: 1 },
        // { label: "按属性查询", value: 2 },
        { label: "按科目查询", value: 3 }
      ],
      currentOption: 1,
      current: 1,
      cropConfig: {
        value: "value",
        label: "name",
        children: "children"
      },
      config: {
        lazy: true,
        lazyLoad(node, resolve) {
          if (node.data.id && node.level < 3) {
            console.log(node.data.id);
            var genusList = [];
            store.dispatch("genus/genusAll", node.data.id).then(response => {
              genusList = response.map(v => {
                return {
                  name: v.genusName,
                  id: v.genusId,
                  leaf: node.level >= 1
                };
              });
              resolve(genusList);
            });
          }
        },
        value: "id",
        label: "name",
        children: "children"
      }
    };
  },
  created() {
    this.getAllFamily();
    this.cropAll();
    this.token = getToken();
    this.getDocument(this.doc);
    this.searchPlant("", this.currentOption);
  },
  methods: {
    //获取所有科
    getAllFamily() {
      this.$store.dispatch("family/lookFamily").then(response => {
        this.familyList = response.map(v => {
          return { name: v.familyName, id: v.familyId };
        });
      });
    },
    getUserByToken() {
      getUserByToken(getToken()).then(response => {
        this.currentUser = response.data;
      });
    },
    showPage() {
      this.updatePasswordVisible = true;
      this.getUserByToken();
    },
    cropAll() {
      this.$store.dispatch("crop/cropAll").then(response => {
        this.cropList = response.map(v => {
          return {
            name: v.cropName,
            value: v.cropId,
            children: v.cropRelations.map(v1 => {
              return {name: v1.commonName, value: v1.commonName};
            })
          };
        });
      });
    },
    updatePassword(user) {
      user.username = this.currentUser.username;
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          updatePassword(user).then(response => {
            if (response.success) {
              this.$message({
                message: "修改密码成功!请重新登录",
                type: "success",
                showClose: true
              });
              removeToken();
              this.updatePasswordVisible = false;
              this.token = "";
            } else {
              this.$message({
                message: response.message,
                type: "success",
                showClose: true
              });
            }
          });
        }
      });
    },
    logout() {
      ElMessageBox.confirm("退出登陆后需要重新登录,是否继续?", "提示", {
        confirmButtonText: "退出",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        removeToken();
        this.$router.push("/login?redirect=/index");
      });
    },
    changName(name) {
      this.$router.push({
        path: "/index",
        query: {plantName: name[1]}
      });
    },
    changSearch(genusId) {
      this.$router.push({
        path: "/index",
        query: { genusId: genusId[1] }
      });
    },
    //获取文献列表
    getDocument(doc) {
      this.$store.dispatch("document/getDocument", doc).then(response => {
        this.documentList = response.records;
      });
    },
    //跳转
    getDocumentById(doc) {
      this.$router.push({
        path: "/pdf",
        query: doc
      });
    },
    searchPlantList(name, type, fun) {
      this.$store
        .dispatch(
          type == 1
            ? "plant/plantByName"
            : type == 2
            ? "genus/getGenusByIdOrByGenusName"
            : "family/familyByName",
          name
        )
        .then(response => {
          fun(response);
        });
    },
    getAutocomplete(queryString, data) {
      this.searchPlantList(queryString, this.currentOption, list => {
        data(list);
      });
    },
    toView(url) {
      this.$router.push({path: url});
    },
    //传递
    searchPlant(name, type) {
      var index;
      if (!name || name == "") {
        this.$router.push({
          path: "/index",
          query: {
            mouth: dayjs().format("MM")
          }
        });
      } else {
        switch (type) {
          case 1:
            index = {plantName: name};
            break;
          case 2:
            index = {genusName: name};
            break;
          default:
            index = {familyName: name};
            break;
        }
        this.$router.push({
          path: "/index",
          query: index
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
body {
  height: 100%;
}

.background {
  height: 100%;
  width: 100%;
  position: fixed;
  background: url("@/assets/bg.png");
  background-size: 100%;
  opacity: 0.85;
}
.el-header {
  width: 100%;
}
::v-deep.el-container {
  display: block;
  width: 100%;
  .main {
    .el-row {
      .right-main {
        background-color: rgba(255, 255, 255, 0.9);
      }
      .el-col {
        border: 1px white solid;
        .message_scrollbar {
          height: 60%;
          // border: 1px solid gray;
        }
        // border: 1px red solid;

        .scroll-content {
          height: 8%;
          .el-scrollbar__wrap {
            height: 100%;
            .el-scrollbar__view {
              white-space: nowrap;
              display: inline-block;
            }
          }
        }
        .el-cascader-panel {
          .el-cascader-menu {
            background-color: transparent;
            color: white;
            min-width: 50%;
            .el-cascader-menu__wrap {
              height: 80vh;
              .el-cascader-node:hover {
                background-color: rgb(108, 107, 107) !important;
                color: yellow;
              }
              .el-cascader-node:active {
                color: yellow;
              }
              .el-cascader-node {
                background-color: rgba(255, 255, 255, 0.8) !important;
                color: black;
              }
            }
          }
        }
      }
    }
  }
}

::v-deep .header-input {
  .el-select__wrapper {
    background-color: rgba(255, 255, 255, 0.8) !important;
    color: white;
    border: 1px solid white;

    .el-select__selection .el-select__selected-item span {
      color: black;
    }
  }

  .el-input {
    .el-input__wrapper {
      background-color: rgba(255, 255, 255, 0.8) !important;
      color: white;
    }

    .el-input-group__append {
      background-color: rgba(255, 255, 255, 0.8) !important;
      color: black;
    }
  }
}
</style>
